import { Component, OnInit } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { UtilService } from "../../my-service/util.service";
import {RollService} from "../../my-service/roll.service";
import { NzMessageService } from 'ng-zorro-antd';
@Component({
  selector: 'app-join-roll',
  templateUrl: './join-roll.component.html',
  styleUrls: ['./join-roll.component.css'],
})
export class JoinRollComponent implements OnInit {
  readImgUrl:string = null;
 joinRoll ={
   search:null,
   isSearch:false,//用户是否进行搜索
   isHaveRoll:false,//是否搜索到数据
   searchRolls:[],//搜索到的花名册
   stuGuid:null,
   InvitationCode:[],//邀请码数组
   codeLength:5,//邀请码长度
 };
  constructor(
  private router:Router,
  private  routerInfo:ActivatedRoute,
  private utilServe:UtilService,
  private rollServe:RollService,
  private msg:NzMessageService
  ) {
    this.readImgUrl = this.utilServe.readImgUrl;
  }
  searchRoll(searchTest){
    this.joinRoll.searchRolls = [];
    this.rollServe.getSearchClassList(searchTest,this.joinRoll.stuGuid).then(res=>{
      if(res.status == 1){
        this.joinRoll.isSearch = true;
        this.joinRoll.searchRolls = res.data;
        if(this.joinRoll.searchRolls.length !== 0){
          this.joinRoll.isHaveRoll = true;
        }
      }else {
        console.log(res);
        this.msg.error('服务器内部错误，请刷新重试');
      }
    })
  }//搜索班级函数
getSearchText(){
  this.joinRoll.search = this.routerInfo.snapshot.params.search;
  if(this.joinRoll.search =='null' || !this.joinRoll.search){
     return false;
  }else{
    return true;
  }
}
getUserGuid () {
  this.utilServe.getUserInfo().then(res=>{
    if(res.status==1){
      this.joinRoll.stuGuid = res.userGuid;
      this.getSearchText();//刷新的时候获取搜索关键字
       if(!this.getSearchText()){
         return false;
       }
      this.searchRoll(this.joinRoll.search);
    }
  })
}
  ngOnInit() {
    this.router.events.subscribe(event=>{
      this.getUserGuid();
    });//路由变化的时候获取搜索关键字
    this.getUserGuid();
  }
  joinClass(InvitationCode,classGuid) {
    if(!(InvitationCode).trim()){
      this.msg.warning('请您输入花名册邀请码再加入花名册');
      return ;
    }
    if((InvitationCode+'').trim().length<this.joinRoll.codeLength){
      this.msg.warning(`花名册邀请码应该为${this.joinRoll.codeLength}位数字`);
      return ;
    }
    let data = {
      InvitationCode,
      FK_ClassGuid:classGuid,
      FK_UserGuid:this.joinRoll.stuGuid
    };
    this.rollServe.joinClass(data).then(res=>{
      if(res.status == 1){
        this.msg.success('您已经成功加入该花名册');
        this.router.navigate(['../start'],{relativeTo:this.routerInfo});
        window.location.reload();
      }else if(res.status==0&&res.err=='邀请码不对'){
        this.msg.error('加入花名册失败，请您核对花名册邀请码');
      }
      else {
        this.msg.error('加入花名册失败，请您核对花名册邀请码');
      }
    })
  }
}
